"""
创建一个新的数据库 dict charset=utf8
数据库dict下创建一个数据表words
表字段 id word mean

create database dict character set utf8;
create table words (
id int primary key auto_increment,
word varchar(32),
mean text 或 varchar(512)
);


请将dict.txt中的单词存入表中
"""
import re

import pymysql

file_path = "dict.txt"  # 相对路径一开始可以,然后不行了
kwargs = {
    'host': 'localhost',
    'port': 3306,
    'user': 'root',
    'password': '123456',
    'database': 'dict',
    'charset': 'utf8'
}

with open(file_path, 'r') as file:
    # 连接数据库\生成游标
    db = pymysql.connect(**kwargs)  # 解压字典传参
    cur = db.cursor()

    # 操作数据 读/写
    data = [
    ]
    for row in file:
        word_mean = re.split(" +", row, 1)
        data.append((word_mean[0], word_mean[1]))

        # 字符串用得好也能处理

        # word_mean = re.split("\s+", row, 1)  # 匹配任意一个空字符
        # print(word_mean)

    try:
        sql = "insert into words (word,mean) values (%s,%s);"
        cur.executemany(sql, data)

        db.commit()
    except Exception as e:
        print(e)
        db.rollback()

    # 关闭游标\断开数据库连接
    cur.close()
    db.close()
